// utils/http.js
const BASE_URL = 'https://manage.youjixiaoyang.com'

// 请求拦截器
const requestInterceptor = (options) => {
  // 可以在这里统一添加请求参数、验证token等
  if (!options.header) options.header = {}
  options.header['token'] = wx.getStorageSync('token') || ''
  return options
}

// 响应拦截器
const responseInterceptor = (response) => {

  // 统一处理响应数据
  if (response.statusCode === 401) {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1];
    const path = `/${currentPage.route}`;
    if(path === '/pages/logs/logs') return
    // token过期处理
    wx.showToast({
      title: '登录已过期，请重新登录',
      icon: 'none'
    })
    wx.navigateTo({
      url: '/pages/logs/logs'
    })
    return Promise.reject(response.data)
  }
  return Promise.resolve(response.data)
}

const http = (options) => {
  // 执行请求拦截
  options = requestInterceptor(options)
  
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: options.header || {
        'Content-Type': 'application/json'
      },
      success(res) {
        // 执行响应拦截
        responseInterceptor(res)
          .then(data => resolve(data))
          .catch(err => reject(err))
      },
      fail(err) {
        // 网络错误处理
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// 添加其他HTTP方法
http.get = (url, data, options = {}) => {
  return http({
    url,
    method: 'GET',
    data,
    ...options
  })
}

http.post = (url, data, options = {}) => {
  return http({
    url,
    method: 'POST',
    data,
    ...options
  })
}

http.put = (url, data, options = {}) => {
  return http({
    url,
    method: 'PUT',
    data,
    ...options
  })
}

http.delete = (url, data, options = {}) => {
  return http({
    url,
    method: 'DELETE',
    data,
    ...options
  })
}

export default http